;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Purchase.PurchaseOrderJck", [])
        .controller("PurchaseOrderJckCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            $scope.activeFlag = [true, false, false, false, false, false, false, false, false, false, false];
            $scope.detailFlag = [true, true];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {
                seller: false
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.isStorage = 0;
            $scope.dataList = [];
            $scope.deliveryWayList = [];
            $scope.detailInfo = {
                crucialDevice: 0,
                entranceDevice: 0
            };
            $scope.filterCondition = {};
            $scope.tabFlag = {};
            var tabFlag = {
                0: "采购申请详情",
                1: "新增采购申请",
                2: "编辑采购申请"
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/purchaseRequest/export"),
                sectionParam: {
                    billIds: []
                },
                allUrl: ybHttp.RequestUrl("device", "/purchaseRequest/exportAll")
            };
            $scope.orderObj = {
                materialsList: [],
                isDirectCast: 0,
                isImprove: 0
            };
            $scope.sourceOrderObj = {
                materialsList: [],
                isDirectCast: 0,
                isImprove: 0
            };
            $scope.purchaseLevelList = [];
            $scope.purchaseOrderTypeList = []; // 采购订单类型
            $scope.billStateList = [];
            $scope.isSap = false;
            $scope.detailMap = [{
                    name: '采购单号',
                    field: 'purchaseNo'
                },
                {
                    name: '接收单位',
                    field: 'supplierOrgName'
                },
                {
                    name: '采购级别',
                    field: 'purchaseLevel'
                },
                {
                    name: '订单状态',
                    field: 'auditState'
                },
                {
                    name: '审核意见',
                    field: 'auditState'
                },
                {
                    name: '采购方式',
                    field: 'purchaseType'
                },
                {
                    name: '发运方式',
                    field: 'dispatchWay'
                },
                {
                    name: '承运商',
                    field: 'dispatchCompany'
                },
                {
                    name: '类型',
                    field: 'type'
                },
                {
                    name: '调度员',
                    field: 'dispatcher'
                },
                {
                    name: '收货人',
                    field: 'receiver'
                },
                {
                    name: '联系人',
                    field: 'contact'
                },
                {
                    name: '传真',
                    field: 'fax'
                },
                {
                    name: '收货地址',
                    field: 'address'
                },
                {
                    name: '出库状态',
                    field: 'warehouseState'
                },
                {
                    name: '申请人',
                    field: 'apply'
                },
                {
                    name: '申请日期',
                    field: 'applyDate'
                },
                {
                    name: '申请部门',
                    field: 'applyDepart'
                },
                {
                    name: '申请人联系方式',
                    field: 'applyContact'
                },
                {
                    name: '备注',
                    field: 'remark'
                }
            ];
            $scope.tableConfig = {
                fixedWidth: 400,
                scrollWidth: 1630,
                tableCol: [{
                        type: "",
                        name: "采购单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "接收单位",
                        dataField: "supplierOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否直投订单",
                        dataField: "isDirectCastShow",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购方式",
                        dataField: "purchaseType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购金额",
                        dataField: "totalValue",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货方式",
                        dataField: "sendType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "createDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditMessage",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购凭证",
                        dataField: "voucherNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synSap",
                        name: "同步状态",
                        dataField: "sapStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        clickFn: "viewSapError",
                        sortType: ""
                    },
                    {
                        type: "attach",
                        name: "附件",
                        dataField: "attachName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "downloadAttach",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购计划单号",
                        dataField: "buyPlanOrder",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否整改",
                        dataField: "isImproveShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 400,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            var materielTableConfig = null;
            $scope.materielTableConfig = {
                scrollWidth: 1780,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    // {
                    //     name: "行号",
                    //     width: 80,
                    //     dataField: "rowNo",
                    //     type: "rowNo",
                    //     needInput: false,
                    // },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "估计重量",
                        width: 120,
                        dataField: "price",
                        needInput: false
                    },
                    {
                        name: "成交单价(￥)",
                        width: 120,
                        dataField: "settlementPrice",
                        input: true,
                        inputType: "price",
                        needInput: false
                    },
                    {
                        type: "storagePlace",
                        name: "库存地点",
                        width: 100,
                        dataField: "enableNum",
                        needInput: false
                    },
                    {
                        type: "storage",
                        name: "可用库存",
                        width: 100,
                        dataField: "enableNum",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: true
                    },
                    {
                        name: "合计(￥)",
                        width: 150,
                        dataField: "applyTotalPrice",
                        needInput: false
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: "deliveryDate",
                        input: true,
                        inputType: "time"
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo"
                    },
                    {
                        name: "改型零件",
                        width: 150,
                        needWarn: true,
                        dataField: "retrofitMaterialsNo"
                    },
                    {
                        name: "备注",
                        width: 130,
                        dataField: "remark",
                        needInput: true,
                        inputType: "remark"
                    }
                ]
            };

            $scope.materielPlanTableConfig = {
                scrollWidth: 1580,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "采购组",
                        width: 100,
                        dataField: "purchaseGroup",
                        needInput: false
                    },
                    {
                        name: "供货商",
                        width: 200,
                        dataField: "purchaseInfoVOList",
                        inputType: "select",
                        needInput: true
                    },
                    {
                        name: "出库频次",
                        width: 80,
                        dataField: "salesRate",
                        needInput: false
                    },
                    {
                        name: "计划数量",
                        width: 100,
                        dataField: "planAmount",
                        needInput: false
                    },
                    {
                        name: "创建订单数量",
                        width: 140,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: true
                    },
                    {
                        name: "交货期",
                        width: 140,
                        dataField: "deliveryDate",
                        input: true,
                        inputType: "time"
                    },
                    {
                        name: "替换零件编号",
                        width: 120,
                        dataField: "replaceMaterialsNo",
                        needInput: false
                    },
                    {
                        name: "替换零件中文名",
                        width: 130,
                        dataField: "replaceMaterialsDes",
                        needInput: false
                    },
                    {
                        name: "备注",
                        width: 130,
                        dataField: "remark",
                        needInput: true,
                        inputType: "remark"
                    }
                ]
            };

            $scope.directMaterielTableConfig = {
                scrollWidth: 1450,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "参考单价(￥)",
                        width: 120,
                        dataField: "price",
                        needInput: false
                    },
                    {
                        name: "成交单价(￥)",
                        width: 120,
                        dataField: "settlementPrice",
                        input: true,
                        inputType: "settlementPrice",
                        needInput: true
                    },
                    {
                        type: "storage",
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: false
                    },
                    {
                        name: "净价",
                        width: 100,
                        dataField: "netPrice",
                        inputType: "netPrice",
                        needInput: true
                    },
                    {
                        name: "合计(￥)",
                        width: 150,
                        dataField: "applyTotalPrice",
                        needInput: false
                    },
                    {
                        name: "交货日期",
                        width: 150,
                        dataField: "deliveryDateStr",
                        needInput: false
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo"
                    },
                    {
                        name: "改型零件",
                        width: 150,
                        needWarn: true,
                        dataField: "retrofitMaterialsNo"
                    }
                ]
            };

            var btnPermissionCode = {
                purchaseOrderJckAdd: window.ActionCode.purchaseOrderJckAdd,
                purchaseOrderJckEdit: window.ActionCode.purchaseOrderJckEdit,
                purchaseOrderJckDel: window.ActionCode.purchaseOrderJckDel,
                purchaseOrderJckCancel: window.ActionCode.purchaseOrderJckCancel,
                purchaseOrderJckCreate: window.ActionCode.purchaseOrderJckCreate,
                purchaseOrderJckUpload: window.ActionCode.purchaseOrderJckUpload,
                purchaseOrderJckBarcode: window.ActionCode.purchaseOrderJckBarcode,
                purchaseOrderJckViewLogistics: window.ActionCode.purchaseOrderJckViewLogistics,
                purchaseOrderJckAutoAdd: window.ActionCode.purchaseOrderJckAutoAdd,
                purchaseOrderJckDirect: window.ActionCode.purchaseOrderJckDirect,
                purchaseOrderJckSapAdd: window.ActionCode.purchaseOrderJckSapAdd,
                purchaseOrderJckExport: window.ActionCode.purchaseOrderJckExport,
            };

            $scope.btnPermission = {
                purchaseOrderJckAdd: true,
                purchaseOrderJckEdit: true,
                purchaseOrderJckDel: true,
                purchaseOrderJckCancel: true,
                purchaseOrderJckCreate: true,
                purchaseOrderJckUpload: true,
                purchaseOrderJckBarcode: true,
                purchaseOrderJckViewLogistics: true,
                purchaseOrderJckAutoAdd: true,
                purchaseOrderJckDirect: true,
                purchaseOrderJckSapAdd: true,
                purchaseOrderJckExport: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                    /*,
                                         purchaseFixedWidth: {left: $scope.purchaseApplyConfig.fixedWidth + "px"}*/
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.materielTableConfig = angular.copy(materielTableConfig);
                        break;
                    case 4:
                        $scope.selectPlan.setFixedWidth();
                        break;
                    case 7:
                        $scope.directPurchasePlan.setFixedWidth();
                        break;
                    case 9:
                        $scope.barCodePage.detailInfo = {};
                        $scope.barCodePage.packList = [];
                        $scope.barCodePage.currentMaterial = {};
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    materialsList: [],
                    isDirectCast: 0,
                    isImprove: 0
                };
                $scope.sourceOrderObj = {
                    materialsList: [],
                    isDirectCast: 0,
                    isImprove: 0
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.detailFlag = [true, true];
                $scope.onlySelect = false;
                $scope.supplierOrgId = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.billIds = [];
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = {
                    billStatus: $scope.condition.billState,
                    supplierOrgName: $scope.condition.supplierOrgName,
                    supplierCode: $scope.condition.supplierCode,
                    purchaseType: $scope.condition.purchaseType,
                    purchaseTypeChildId: $scope.condition.purchaseTypeChildId,
                    billNo: $scope.condition.billNo,
                    createDateStart: $scope.condition.createDateStart,
                    createDateEnd: $scope.condition.createDateEnd,
                    dispatcherName: $scope.condition.dispatcherName,
                    buyPlanOrder: $scope.condition.buyPlanOrder,
                    isDirectCast: $scope.condition.isDirectCast,
                    directSourceOrder: $scope.condition.directSourceOrder,
                    sapStatus: $scope.condition.sapStatus,
                    materialsNo: $scope.condition.materialsNo,
                    voucherNo: $scope.condition.voucherNo,
                    createName: $scope.condition.createName,
                    seller: false
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.sapStatusShow = $filter("ProgressStatus")(item.sapStatus, "sap");
                        item.isDirectCastShow = $filter("TrueOrFalse")(item.isDirectCast);
                        item.purchaseType = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                        item.sendType = item.sendTypeChildId ? item.shippingMethod + "-" + item.sendTypeChildName : item.shippingMethod;
                        item.isImproveShow = $filter("TrueOrFalse")(item.isImprove);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    case "downloadAttach":
                        downloadAttach(item);
                        break;
                    default:
                        break;
                }
            };

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            function downloadAttach(item) {
                window.location.href = ybHttp.RequestUrl("device", "/purchaseRequest/downloadAttach") + '?billId=' + item.billId;
            }

            function getPurchaseLevel() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "CGJB"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.purchaseLevelList = resp.value;
                })
            }

            function getPurchaseOrderType() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "CGDDLX"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.purchaseOrderTypeList = resp.value;
                })
            }

            function getOrderStatues() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "SPZT"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.billStateList = resp.value;
                })
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    seller: false
                };
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };

            function getDetail(item, type) {
                var param = {
                    billId: item.billId
                };
                return ybHttp.Get('device', '/purchaseRequest/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (!resp.value) return null;
                    angular.forEach(resp.value.materialsList, function (item) {
                        item.oldQty = item.qty;
                        item.deliveryDate = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    resp.value.sapStatusShow = $filter("ProgressStatus")(resp.value.sapStatus, "sap");
                    return resp.value;
                });
            }

            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }

                    $scope.orderObj = data;
                    $scope.orderObj.isPlatCompany = $scope.orderObj.platCompany;
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.deliveryDate = item.deliveryDate.substring(0, 10);
                    });
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    if (item.billStatus === '2') {
                        $scope.changeTab(10);
                    } else {
                        $scope.changeTab(2);
                    }
                    getIsStorage();
                    //clearMateriel();
                });
            };
            $scope.adjustApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }

                    $scope.orderObj = data;
                    $scope.orderObj.isPlatCompany = $scope.orderObj.platCompany;
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.deliveryDate = item.deliveryDate.substring(0, 10);
                    });
                    $scope.changeTab(12);
                    getIsStorage();
                    //clearMateriel();
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.changeTab(3);
                    getIsStorage('detail');
                });
            }

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialsList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialsList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialsList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialsList[i].isChecked) {
                            $scope.orderObj.materialsList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialsList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.countTotal = function (item) {
                item.qtyErr = false;
                item.qtyFormatErr = false;
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                    item.qtyFormatErr = true;
                    return;
                }
                if (item.qty > 99999.999) {
                    item.qty = 99999.999;
                }
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            };

            $scope.countTotalEdit = function (item) {
                item.qtyErr = false;
                item.qtyFormatErr = false;
                item.qtyEditErr = false;
                item.qtyMaxErr = false;
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                    item.qtyFormatErr = true;
                    return;
                }
                if (item.qty < item.sendQty) {
                    item.qtyEditErr = true;
                    return;
                }
                if (item.qty > item.oldQty) {
                    item.qtyMaxErr = true;
                    return;
                }

                if (item.qty > 99999.999) {
                    item.qty = 99999.999;
                }
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            };

            EventBus.Subscribe("onMaterialChange", calcOrderTotalValue);

            function calcOrderTotalValue() {
                $scope.orderObj.totalValue = 0;
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    $scope.orderObj.totalValue += (+item.applyTotalPrice || 0);
                });
                $scope.orderObj.totalValue = $filter("decimalCover")($scope.orderObj.totalValue, 2);
            }

            $scope.countNetPriceTotal = function (item) {
                if (item.netPrice > 99999.999) {
                    item.netPrice = 99999.999;
                }
            };

            $scope.countPriceTotal = function (item) {
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.settlementPrice, item.qty), 2);
                var totalValue = 0;
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    totalValue += +item.applyTotalPrice;
                });
                $scope.orderObj.totalValue = totalValue;
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/purchaseRequest/remove";
                    var param = {};
                    param.billId = item.billId;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.orderObj.createDate = +new Date();
                $scope.orderObj.purchaseOrgName = $scope.curOrg.companyName;
                $scope.changeTab(2);
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    if (!$scope.orderObj.supplierOrgName) {
                        ybWidget.ShowToaster('error', '请选择接收单位');
                        return;
                    }
                    if ($scope.orderObj.isDirectCast == 1 && !$scope.orderObj.soldOrgName) {
                        ybWidget.ShowToaster('error', '请选择供货商');
                        return;
                    }
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                if (!$scope.orderObj.supplierOrgName) {
                    ybWidget.ShowToaster('error', '请选择接收单位');
                    return;
                }
                if ($scope.orderObj.isDirectCast && !$scope.orderObj.soldOrgId) {
                    ybWidget.ShowToaster('error', '请选择供货商');
                    return;
                }
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/download",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/import",
                    importErrorUrl: "",
                    orgId: $scope.orderObj.supplierOrgId,
                    soldOrgId: $scope.orderObj.soldOrgId,
                    isDirectCast: $scope.orderObj.isDirectCast,
                    supplierCode: $scope.orderObj.supplierCode
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.materialsList = [];
                    $scope.orderObj.materialsList = angular.copy(data);
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.qtyFormatErr = false;
                        if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                            item.qtyFormatErr = true;
                        }
                    });
                });
            };
            $scope.saveData = function (type, invalid, isPlan) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                // for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                //     if (!$scope.orderObj.materialsList[i].settlementPrice || $scope.orderObj.materialsList[i].settlementPrice <= 0) {
                //         return;
                //     }
                // }
                var listValid = true;
                var service = "device";
                var reqUrl = "/purchaseRequest/save";
                if (type === 'submit') {
                    reqUrl = "/purchaseRequest/submit";
                    if (!$scope.orderObj.materialsList || $scope.orderObj.materialsList.length == 0) {
                        ybWidget.ShowToaster('error', '零件不可为空');
                        return;
                    }
                }
                var param = angular.copy($scope.orderObj);
                param.shippingMethod = $scope.orderObj.shippingMethod;
                param.seller = false;

                if (!!isPlan) {
                    reqUrl = "/purchaseRequest/saveByPlan";
                    param.billStatus = type === 'submit' ? '1' : '0';
                }

                var errMsgStr = "";
                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    $scope.orderObj.materialsList[i].qtyErr = false;
                    $scope.orderObj.materialsList[i].qtyFormatErr = false;
                    $scope.orderObj.materialsList[i].dateErr = false;
                    if (!$scope.orderObj.materialsList[i].qty || parseFloat($scope.orderObj.materialsList[i].qty) <= 0) {
                        $scope.orderObj.materialsList[i].qtyErr = true;
                        listValid = false;
                        errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量不能为空和0";
                        break;
                    }
                    if ($scope.orderObj.isDirectCast === 1 && $scope.orderObj.materialsList[i].isMinimumBuy && ybWidget.Remainder($scope.orderObj.materialsList[i].qty, $scope.orderObj.materialsList[i].minimumBuy) > 0) {
                        $scope.orderObj.materialsList[i].qtyFormatErr = true;
                        listValid = false;
                        errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量必须为最小购买量" + $scope.orderObj.materialsList[i].minimumBuy + "的倍数";
                        break;
                    }

                    if ($scope.activeFlag[10]) {
                        if ($scope.orderObj.materialsList[i].qty < $scope.orderObj.materialsList[i].sendQty) {
                            $scope.orderObj.materialsList[i].qtyEditErr = true;
                            listValid = false;
                            errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量不能小于已建入库单数量";
                            break;
                        }
                        if ($scope.orderObj.materialsList[i].qty > $scope.orderObj.materialsList[i].oldQty) {
                            $scope.orderObj.materialsList[i].qtyMaxErr = true;
                            listValid = false;
                            errMsgStr = "零件" + $scope.orderObj.materialsList[i].materialsNo + "：申请数量不能大于原数量";
                            break;
                        }
                    }
                }
                if (!listValid) {
                    ybWidget.ShowMessage(errMsgStr, MESG_TYPE.Error);
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };


            $scope.adjustData = function (invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }

                var listValid = true;
                var service = "device";
                var reqUrl = "/purchaseRequest/adjust";

                if (!$scope.orderObj.materialsList || $scope.orderObj.materialsList.length == 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }


                var param = angular.copy($scope.orderObj);
                param.shippingMethod = $scope.orderObj.shippingMethod;
                param.seller = false;

                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    $scope.orderObj.materialsList[i].qtyErr = false;
                    $scope.orderObj.materialsList[i].qtyFormatErr = false;
                    $scope.orderObj.materialsList[i].dateErr = false;
                    if (!$scope.orderObj.materialsList[i].qty || parseFloat($scope.orderObj.materialsList[i].qty) <= 0) {
                        $scope.orderObj.materialsList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                    if ($scope.orderObj.isDirectCast === 1 && $scope.orderObj.materialsList[i].isMinimumBuy && ybWidget.Remainder($scope.orderObj.materialsList[i].qty, $scope.orderObj.materialsList[i].minimumBuy) > 0) {
                        $scope.orderObj.materialsList[i].qtyFormatErr = true;
                        listValid = false;
                        break;
                    }

                }
                if (!listValid) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };


            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.selectSupplier = function (notClearMateriel) {
                var param = {
                    name: "接收单位",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    // 如果值为空或者选择相同的接收单位直接返回不做后续处理
                    if (!data.supplierOrgId || data.supplierOrgId === $scope.orderObj.supplierOrgId) {
                        return;
                    }
                    $scope.orderObj.dispatcherName = "";
                    $scope.orderObj.dispatcherId = "";
                    $scope.orderObj.purchaseType = "";
                    $scope.orderObj.purchaseTypeName = "";
                    $scope.orderObj.purchaseTypeChildId = "";
                    $scope.orderObj.purchaseTypeChildName = "";

                    // 修改接收单位清空供货商
                    $scope.orderObj.soldOrgId = "";
                    $scope.orderObj.soldOrgName = "";
                    if (!notClearMateriel) {
                        clearPriceScheme();
                    }

                    $scope.orderObj.supplierCode = data.supplierCode;
                    $scope.orderObj.supplierOrgId = data.supplierOrgId;
                    $scope.orderObj.supplierOrgName = data.companyName;
                    $scope.orderObj.drawerOrgId = data.supplierOrgId;
                    $scope.orderObj.drawerOrgName = data.companyName;
                    $scope.orderObj.isPlatCompany = data.isPlatCompany;
                    $scope.isSap = data.isSap === 1;

                    if (data.isSap && window.WJ_ORG_IDs.includes(data.supplierOrgId)) {
                        $scope.onlySelect = true;
                        $scope.orderObj.receiverName = "";
                        $scope.orderObj.receiverTel = "";
                        $scope.orderObj.receiverAddress = "";
                    }

                    // 重新选择接收单位后 清除零件并查询该接收单位下的零件
                    clearMateriel();
                    getIsStorage();
                    getDirectLimit();
                })
            };

            $scope.clearSupplier = function (notClearMateriel) {
                $scope.orderObj.supplierOrgId = "";
                $scope.orderObj.supplierOrgName = "";
                $scope.orderObj.drawerOrgId = "";
                $scope.orderObj.drawerOrgName = "";
                $scope.orderObj.dispatcherName = "";
                $scope.orderObj.dispatcherId = "";
                $scope.orderObj.directLimit = 0;
                // 清空接收单位清空供货商
                $scope.orderObj.soldOrgId = "";
                $scope.orderObj.soldOrgName = "";
                if (!notClearMateriel) {
                    clearMateriel();
                }
            };

            $scope.selectDirectSupplier = function () {
                var param = {
                    name: "供货商",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    getDirectMaterials(data.supplierOrgId).then(function (arr) {
                        if (arr.length > 0) {
                            ybWidget.ShowMessage("该供货商下不存在此零件：" + arr.toString(), MESG_TYPE.Error);
                            return;
                        }
                        if (!!$scope.orderObj.supplierOrgId && (data.supplierOrgId !== $scope.orderObj.supplierOrgId)) {
                            $scope.orderObj.dispatcherName = "";
                            $scope.orderObj.dispatcherId = "";
                            $scope.orderObj.purchaseType = "";
                            $scope.orderObj.purchaseTypeName = "";
                            $scope.orderObj.purchaseTypeChildId = "";
                            $scope.orderObj.purchaseTypeChildName = "";
                        }
                        $scope.orderObj.supplierOrgId = data.supplierOrgId;
                        $scope.orderObj.supplierOrgName = data.companyName;
                        $scope.orderObj.soldOrgId = data.supplierOrgId;
                        $scope.orderObj.soldOrgName = data.companyName;
                        $scope.orderObj.drawerOrgId = data.supplierOrgId;
                        $scope.orderObj.drawerOrgName = data.companyName;
                        $scope.orderObj.isPlatCompany = data.isPlatCompany;
                        $scope.isSap = data.isSap === 1;

                        if (data.isSap && window.WJ_ORG_IDs.includes(data.supplierOrgId)) {
                            $scope.onlySelect = true;
                            $scope.orderObj.receiverName = "";
                            $scope.orderObj.receiverTel = "";
                            $scope.orderObj.receiverAddress = "";
                        }

                        getIsStorage();
                        getDirectLimit();
                    });
                })
            };

            function getDirectMaterials(suppleriOrgId) {
                var service = "device";
                var reqUrl = "/materials/purchaseMaterialsList";
                var materialsNos = getMateraisNos();
                var param = {};
                param.filters = {
                    isDirectCast: 1,
                    dealerOrgId: $scope.orderObj.deliveryOrgId,
                    supplierOrgId: suppleriOrgId,
                    materialsNos: materialsNos
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var arr = [];
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        var flag = true;
                        for (var i = 0; i < resp.value.list.length; i++) {
                            if (item.materialsNo === resp.value.list[i].materialsNo) {
                                flag = false;
                            }
                        }
                        if (flag) {
                            arr.push(item.materialsNo);
                        }
                    });
                    return arr;
                });
            }

            function getMateraisNos() {
                var materaisNos = "";
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    materaisNos = materaisNos + item.materialsNo + ",";
                });
                if (materaisNos.length > 1) {
                    materaisNos = materaisNos.substring(0, materaisNos.length - 1);
                }
                return materaisNos;
            }

            $scope.selectSold = function () {
                if (!$scope.orderObj.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请先选择接收单位');
                    return;
                }
                var param = {
                    name: "供货商",
                    type: "supplier",
                    soldOrgId: $scope.orderObj.supplierOrgId,
                    isDirect: 1,
                    purchaseOrder: true
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    // 若果返回的是控制或者选择的是相同的供货商直接返回
                    if (!data.supplierOrgId || $scope.orderObj.soldOrgId === data.supplierOrgId) {
                        return;
                    }
                    $scope.orderObj.soldOrgId = data.supplierOrgId;
                    $scope.orderObj.soldOrgName = data.shortName;

                    getIsStorage();
                    //重新选择供货商后 清空零件
                    clearMateriel();
                })
            };

            $scope.clearSold = function () {
                $scope.orderObj.soldOrgId = "";
                $scope.orderObj.soldOrgName = "";
                clearMateriel();
            };

            $scope.selectDrawer = function () {
                var param = {
                    name: "出票方",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.drawerOrgId = data.supplierOrgId;
                    $scope.orderObj.drawerOrgName = data.companyName;
                })
            };

            $scope.clearDrawer = function () {
                $scope.orderObj.drawerOrgId = "";
                $scope.orderObj.drawerOrgName = "";
            };

            $scope.selectPurchaseGroup = function () {
                var param = {
                    name: "采购组",
                    type: "purchaseGroup"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.purchaseGroup = data.code;
                })
            };

            $scope.clearPurchaseGroup = function () {
                $scope.orderObj.purchaseGroup = "";
            };

            function clearMateriel() {
                if (!!$scope.orderObj.buyPlanOrder) {
                    return;
                }
                $scope.orderObj.materialsList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    if (!$scope.orderObj.supplierOrgId) {
                        EventBus.Publish("clearMaterial");
                    } else if ($scope.orderObj.isDirectCast == 1 && !$scope.orderObj.soldOrgName) {
                        EventBus.Publish("clearMaterial");
                    } else if ($scope.orderObj.isDirectCast == 0 && $scope.orderObj.supplierOrgId) {
                        // 不是直投订单，选择了接收单位就重新获取零件
                        EventBus.Publish("getMaterial");
                    } else if ($scope.orderObj.isDirectCast == 1 && $scope.orderObj.supplierOrgId && $scope.orderObj.soldOrgName) {
                        // 直投订单，选择了接收单位和供货商就重新获取零件
                        EventBus.Publish("getMaterial");
                    }
                });
            }

            $scope.selectDispatch = function () {
                if (!$scope.orderObj.supplierOrgId) {
                    ybWidget.ShowToaster('error', '请先选择接收单位');
                    return;
                }
                var param = {
                    name: "调度员",
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.orderObj.supplierOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.dispatcherName = data.name;
                    $scope.orderObj.dispatcherId = data.userId;
                })
            };

            $scope.selectDispatchPerson = function () {
                var param = {
                    name: "调度员",
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.orderObj.orgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.dispatcherName = data.name;
                    $scope.orderObj.dispatcherId = data.userId;
                })
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.billIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.billIds.push(item.billId);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.chosePriceScheme = function (item, index) {
                var clientId = $scope.orderObj.supplierOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择接收单位');
                    return;
                }
                
                var param = {
                    schemeType: 1,
                    selectedDisabled: !$scope.isZHJCH && window.WJ_ORG_IDs.includes(clientId),
                    apiObj: {
                        param: {
                            supplierOrgId: clientId,
                            materialsNo: item.materialsNo,
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    setPriceScheme(item, data);
                })
            };

            function setPriceScheme(item, priceScheme) {
                item.priceSchemeId = priceScheme.activityId;
                item.priceSchemeName = priceScheme.name;

                item.settlementPrice = $filter("decimalCover")(priceScheme.discountPrice, 2);
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            }

            function clearPriceScheme() {
                if (!!$scope.orderObj.buyPlanOrder) {
                    return;
                }
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    item.priceSchemeId = "";
                    item.priceSchemeName = "";
                    item.settlementPrice = item.price;
                    item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                });
                calcOrderTotalValue();
            }

            $scope.clearPriceScheme = function (item) {
                item.priceSchemeId = "";
                item.priceSchemeName = "";
                item.settlementPrice = item.price;
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            };

            function getIsStorage(type) {
                var service = "device";
                var reqUrl = "/companyDealer/isStorage";
                var param = {
                    orgId: $scope.orderObj.supplierOrgId
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    $scope.isStorage = resp;
                    if ($scope.isStorage === '0') {
                        $scope.materielTableConfig.scrollWidth = 1680;
                        $scope.materielTableConfig.tableCol = [];
                        angular.forEach(materielTableConfig.tableCol, function (item) {
                            if (item.type !== 'storage') {
                                $scope.materielTableConfig.tableCol.push(angular.copy(item));
                            }
                        });
                    } else {
                        $scope.materielTableConfig = angular.copy(materielTableConfig);
                    }

                    if (type === 'detail') {
                        hideCol();
                    }
                })
            }

            function getDirectLimit() {
                var service = "device";
                var reqUrl = "/companyDealer/getDirectLimit";
                var param = {
                    orgId: $scope.orderObj.supplierOrgId
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    $scope.orderObj.directLimit = resp;
                })
            }

            function hideCol() {
                var tempCol = angular.copy($scope.materielTableConfig.tableCol);
                $scope.materielTableConfig.scrollWidth = 1380;
                $scope.materielTableConfig.tableCol = [];
                angular.forEach(tempCol, function (item) {
                    if (['replaceMaterialsNo', 'retrofitMaterialsNo'].indexOf(item.dataField) === -1) {
                        $scope.materielTableConfig.tableCol.push(angular.copy(item));
                    }
                });
            }

            $scope.switchListDatePicker = function (item) {
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    item.showDatePicker = false;
                });
                item.showDatePicker = true;
            };

            $scope.sapPost = function (item) {
                var service = "device";
                var reqUrl = "/purchaseRequest/sapPost";
                var param = {};
                param.billId = item.billId;
                ybWidget.ShowMessage("确定要创建采购凭证吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.cancelApply = function (item) {
                var service = "device";
                var reqUrl = "/purchaseRequest/cancel";
                var param = {};
                param.billId = item.billId;
                ybWidget.ShowMessage("确定要撤销该采购订单吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.importAttach = function (item) {
                var param = {
                    name: "附件",
                    hideTemplate: true,
                    ignoreFormat: true,
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importAttach",
                    importErrorUrl: "",
                    billId: item.billId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            //自动新增采购订单
            $scope.autoAddApply = function () {
                //代理商和主机厂不同处理
                if (!$scope.isZHJCH) {
                    getAgentPlanDataList();
                    $scope.changeTab(11);
                } else {
                    getPlanDataList(1);
                    $scope.changeTab(4);
                }
            };

            // 代理商 自动填充采购订单信息
            $scope.agentMakeIntention = function (planInfo) {
                // 获取采购计划详情信息
                getAgentPlanDetail(planInfo).then(function (res) {
                    if (!res) {
                        return;
                    }
                    // 填充新增采购申请页面的信息
                    $scope.orderObj = {
                        purchaseOrgName: res.headerInfo.deptName,
                        buyPlanOrder: res.headerInfo.planNo,
                        remark: res.headerInfo.remark,
                        isDirectCast: 0,
                        materialsList: res.detailList
                    };
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.settlementPrice = item.price;
                        item.enableNum = item.stock;
                        item.qty = item.adjustQty;
                        item.applyTotalPrice = item.adjustAmount;
                    });
                    // 计算订单总额
                    calcOrderTotalValue();
                    // 跳转到新增采购申请页签
                    $scope.addApply();
                });
            }

            $scope.makeIntention = function (planInfo) {
                getPlanDataInfo(planInfo).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = {
                        purchaseOrgName: data.headerInfo.deptName,
                        createDate: data.headerInfo.createDate,
                        purchaseType: data.headerInfo.typeId,
                        purchaseTypeChildId: data.headerInfo.purchaseTypeChildId,
                        remark: data.headerInfo.note,
                        isDirectCast: 0,
                        materialsList: data.materialList,
                        buyPlanOrder: data.headerInfo.planOrder,
                        supplierList: data.headerInfo.supplierList,
                        isImprove: 0,
                        orgId: data.headerInfo.orgId
                    };
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.settlementPrice = item.price;
                        item.applyTotalPrice = item.totalPrice;
                        item.planAmount = item.qty;
                    });
                    $scope.sourceOrderObj = angular.copy($scope.orderObj);
                    calcOrderTotalValue();
                    $scope.changeTab(5);
                });
            };

            //代理商采购计划信息
            $scope.agentPlan = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                condition: {},
                dataList: [],
                toolbarConfig: {
                    showAdvanceSearch: false,
                    showColConfig: false,
                    showMateriel: false
                },
                tableConfig: {
                    fixedWidth: 150,
                    scrollWidth: 920,
                    tableCol: [{
                            type: "",
                            name: "采购计划单号",
                            dataField: "planNo",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "采购类型",
                            dataField: "typeDesc",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "制单人",
                            dataField: "createName",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "审核人",
                            dataField: "auditName",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "审核时间",
                            dataField: "auditTimeShow",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "备注",
                            dataField: "remark",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: false,
                            sortType: ""
                        },
                        {
                            type: "operate",
                            name: "操作",
                            dataField: "",
                            width: 120,
                            isShow: true,
                            isFixed: true,
                            toSort: false,
                            sortType: ""
                        }
                    ]
                },
                //搜索
                search: function (curPage) {
                    getAgentPlanDataList(curPage);
                },
                //重置搜索条件
                reset: function () {
                    $scope.agentPlan.condition = {};
                },
                //隐藏和展示高级搜索
                switchToolbar: function (toolbar) {
                    if (!!$scope.agentPlan.toolbarConfig["show" + toolbar]) {
                        $scope.agentPlan.toolbarConfig["show" + toolbar] = false;
                    } else {
                        $timeout(function () {
                            $scope.agentPlan.toolbarConfig["show" + toolbar] = true;
                        });
                    }
                },
                //设置表格列的宽度
                setFixedWidth: function () {
                    $scope.agentPlan.tbStyle = {
                        sellFixedWidth: {
                            left: $scope.selectPlan.tableConfig.fixedWidth + "px"
                        }
                    };
                },
            };

            //主机厂采购计划信息
            $scope.selectPlan = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                markInfo: {},
                condition: {},
                dataList: [],
                toolbarConfig: {
                    showAdvanceSearch: false,
                    showColConfig: false,
                    showMateriel: false
                },
                tableConfig: {
                    fixedWidth: 120,
                    scrollWidth: 920,
                    tableCol: [{
                            type: "",
                            name: "采购计划单号",
                            dataField: "planOrder",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请人",
                            dataField: "createName",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请部门",
                            dataField: "deptName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请时间",
                            dataField: "createDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "采购方式",
                            dataField: "purchaseType",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "备注",
                            dataField: "note",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "审核状态",
                            dataField: "auditStatusShow",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "operate",
                            name: "操作",
                            dataField: "",
                            width: 120,
                            isShow: true,
                            isFixed: true,
                            toSort: false,
                            sortType: ""
                        }
                    ]
                },

                search: function (curPage) {
                    getPlanDataList(curPage);
                },
                reset: function () {
                    $scope.selectPlan.condition = {};
                },
                switchToolbar: function (toolbar) {
                    if (!!$scope.selectPlan.toolbarConfig["show" + toolbar]) {
                        $scope.selectPlan.toolbarConfig["show" + toolbar] = false;
                    } else {
                        $timeout(function () {
                            $scope.selectPlan.toolbarConfig["show" + toolbar] = true;
                        });
                    }
                },
                setFixedWidth: function () {
                    $scope.selectPlan.tbStyle = {
                        sellFixedWidth: {
                            left: $scope.selectPlan.tableConfig.fixedWidth + "px"
                        }
                    };
                },
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                selectRow: function (index) {
                    $scope.selectPlan.markInfo.cueRow = index
                },
            };

            //获取代理商审核通过的汇总采购计划列表
            function getAgentPlanDataList(pageNum) {
                var url = '/agentPlan/list4PurchaseRequest';
                var service = "device";
                //遍历搜索条件对象里的空值并删除  不然搜索不出数据
                Object.keys($scope.agentPlan.condition).forEach(function (key) {
                    if (!$scope.agentPlan.condition[key]) delete $scope.agentPlan.condition[key];
                });
                var param = {
                    pageSize: $scope.agentPlan.pageInfo.pageSize,
                    pageNum: pageNum || $scope.agentPlan.pageInfo.pageSize,
                    filters: $scope.agentPlan.condition
                };
                ybHttp.Post(service, url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(res.value.pageInfoList, function (item) {
                        item.auditTimeShow = $filter("YbDate")(item.auditTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.agentPlan.pageInfo.totalRows = res.value.pageInfo.total;
                    $scope.agentPlan.pageInfo.totalPages = res.value.pageInfo.pages;
                    $scope.agentPlan.dataList = res.value.pageInfoList;
                })
            }

            function getPlanDataList(curPage) {
                var service = "device";
                var reqUrl = "/buyPlan/list";
                var param = {};
                param.pageSize = $scope.selectPlan.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.selectPlan.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.selectPlan.pageInfo.curPage;
                param.filters = angular.copy($scope.selectPlan.condition);
                param.filters.auditStatus = 1;
                param.filters.notComplete = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditStatusShow = $filter("ProgressStatus")(item.auditStatus, "audit");
                        item.purchaseType = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                    });
                    $scope.selectPlan.pageInfo.totalRows = resp.value.total;
                    $scope.selectPlan.pageInfo.totalPages = resp.value.pages;
                    $scope.selectPlan.dataList = resp.value.list;
                });
            }

            function getPlanDataInfo(planInfo) {
                var param = {
                    id: planInfo.id
                };
                return ybHttp.Get('device', '/buyPlan/itemForPurchase', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            //获取代理商采购计划详情
            function getAgentPlanDetail(planInfo) {
                var param = {
                    planId: planInfo.id
                };
                return ybHttp.Get('device', '/agentPlan/select4PurchaseOrder', param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    return res.value;
                });
            }

            $scope.sapAddObj = {};
            $scope.sapAddSubmitted = false;
            $scope.sapAdd = function () {
                $scope.sapAddSubmitted = false;
                $scope.sapAddObj = {};
                $scope.changeTab(6);
            };
            $scope.saveSapAddData = function (invalid) {
                if (!invalid) {
                    $scope.sapAddSubmitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/purchaseRequest/sapAdd";
                var param = angular.copy($scope.sapAddObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.changeTab(0);
                    var errorList = resp.value || [];
                    if (errorList.length > 0) {
                        ybWidget.ShowMessage(errorList.join("<br />"), MESG_TYPE.Error, {
                            isHtml: true
                        });
                    } else {
                        ybWidget.ShowToaster('success', '操作成功');
                    }
                });
            };

            /*直投采购计划*/
            $scope.directAddApply = function () {
                getDircectPurchasePlanDataList(1);
                $scope.changeTab(7);
            };
            $scope.directPurchasePlan = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                markInfo: {},
                condition: {},
                dataList: [],
                toolbarConfig: {
                    showAdvanceSearch: false,
                    showColConfig: false,
                    showMateriel: false
                },
                tableConfig: {
                    fixedWidth: 120,
                    scrollWidth: 920,
                    tableCol: [{
                            type: "",
                            name: "采购订单号",
                            dataField: "billNo",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请单位",
                            dataField: "purchaseOrgName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "供货商",
                            dataField: "soldOrgName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "直投达标金额",
                            dataField: "directLimit",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "备注",
                            dataField: "remark",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请时间",
                            dataField: "createDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "operate",
                            name: "操作",
                            dataField: "",
                            width: 120,
                            isShow: true,
                            isFixed: true,
                            toSort: false,
                            sortType: ""
                        }
                    ]
                },

                search: function (curPage) {
                    getDircectPurchasePlanDataList(curPage);
                },
                reset: function () {
                    $scope.directPurchasePlan.condition = {};
                },
                switchToolbar: function (toolbar) {
                    if (!!$scope.directPurchasePlan.toolbarConfig["show" + toolbar]) {
                        $scope.directPurchasePlan.toolbarConfig["show" + toolbar] = false;
                    } else {
                        $timeout(function () {
                            $scope.directPurchasePlan.toolbarConfig["show" + toolbar] = true;
                        });
                    }
                },
                setFixedWidth: function () {
                    $scope.directPurchasePlan.tbStyle = {
                        sellFixedWidth: {
                            left: $scope.directPurchasePlan.tableConfig.fixedWidth + "px"
                        }
                    };
                },
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                selectRow: function (index) {
                    $scope.directPurchasePlan.markInfo.cueRow = index
                }
            };

            function getDircectPurchasePlanDataList(curPage) {
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                var param = {};
                param.pageSize = $scope.directPurchasePlan.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.directPurchasePlan.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.directPurchasePlan.pageInfo.curPage;
                param.filters = angular.copy($scope.directPurchasePlan.condition);
                param.filters.seller = true;
                param.filters.billStatus = "2";
                param.filters.isDirectAdd = 0;
                param.filters.isDirectCast = 1;
                param.filters.onlyDirect = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.directPurchasePlan.pageInfo.totalRows = resp.value.total;
                    $scope.directPurchasePlan.pageInfo.totalPages = resp.value.pages;
                    $scope.directPurchasePlan.dataList = resp.value.list;
                });
            }

            function getDircectPurchasePlanDataInfo(planInfo) {
                var param = {
                    billId: planInfo.billId,
                    isDirect: 1
                };
                return ybHttp.Get('device', '/purchaseRequest/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            $scope.createDirectPurchaseOrder = function (planInfo) {
                getDircectPurchasePlanDataInfo(planInfo).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = angular.copy(data);
                    $scope.orderObj.purchaseOrgId = data.supplierOrgId;
                    $scope.orderObj.purchaseOrgName = data.supplierOrgName;
                    $scope.orderObj.supplierOrgId = $scope.orderObj.soldOrgId;
                    $scope.orderObj.supplierOrgName = $scope.orderObj.soldOrgName;
                    $scope.orderObj.deliveryOrgId = data.purchaseOrgId;
                    $scope.orderObj.deliveryOrgName = data.purchaseOrgName;
                    $scope.orderObj.directSourceOrder = data.billNo;
                    $scope.orderObj.directSourceId = data.billId;
                    $scope.orderObj.dispatcherName = '';
                    $scope.orderObj.dispatcherId = '';
                    $scope.orderObj.billId = '';
                    $scope.orderObj.billNo = '';

                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.deliveryDateStr = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.changeTab(8);
                    $scope.orderObj.purchaseOrdType = 'NB';
                    $scope.orderObj.purchaseOrdTypeDesc = '一般采购';
                });
            };

            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("onMaterialChange", calcOrderTotalValue);
            });

            $scope.barCodePage = {
                dataList: [],
                detailInfo: {},
                packList: [],
                currentMaterial: {},
                markInfo: {},
                tableConfig: {
                    scrollWidth: 720,
                    tableCol: [{
                            type: "",
                            name: "打印标志",
                            dataField: "stateName",
                            width: 90
                        },
                        {
                            type: "",
                            name: "零件编号",
                            dataField: "materialsNo",
                            width: 120
                        },
                        {
                            type: "",
                            name: "零件中文名",
                            dataField: "materialsDes",
                            width: 120
                        },
                        {
                            type: "",
                            name: "数量",
                            dataField: "qty",
                            width: 80
                        },
                        {
                            type: "",
                            name: "未打数量",
                            dataField: "restAmount",
                            width: 100
                        },
                        {
                            type: "",
                            name: "操作标志",
                            dataField: "statusName",
                            width: 90
                        }
                    ]
                },
                countPack: function () {
                    $scope.barCodePage.detailInfo.packNum = parseFloat($scope.barCodePage.detailInfo.packNum);
                    if ($scope.barCodePage.detailInfo.totalQty > $scope.barCodePage.currentMaterial.restAmount) {
                        $scope.barCodePage.detailInfo.totalQty = $scope.barCodePage.currentMaterial.restAmount;
                    }
                    setEachPack();
                },
                setPackNum: function () {
                    $scope.barCodePage.detailInfo.packNum = parseInt($scope.barCodePage.detailInfo.packNum);
                    setEachPack();
                },
                selectRow: function (index) {
                    if ($scope.barCodePage.dataList[index].printState == 2) {
                        ybWidget.ShowToaster('error', '请选择条码生成未完成的零件');
                        return;
                    }
                    $scope.barCodePage.markInfo.cueRow = index;
                    $scope.barCodePage.currentMaterial = $scope.barCodePage.dataList[index];
                    $scope.barCodePage.detailInfo.totalQty = angular.copy($scope.barCodePage.currentMaterial.restAmount);
                    $scope.barCodePage.detailInfo.packNum = 1;
                    $scope.barCodePage.packList = [{
                        currentQty: $scope.barCodePage.currentMaterial.restAmount,
                        vinid: ''
                    }];
                }
            };
            var currentBillItem = null;
            $scope.createBarcode = function (item) { // 生成条码
                getDetail(item).then(function (billDetail) {
                    if (!billDetail) {
                        return;
                    }
                    currentBillItem = item;
                    $scope.barCodePage.detailInfo = {};
                    $scope.barCodePage.markInfo.cueRow = null;
                    angular.forEach(billDetail.materialsList, function (item) {
                        item.stateName = $filter('printState')(item.printState);
                        item.statusName = $filter('allotState')(item.printState);
                        item.restAmount = item.qty - (item.printNum || 0);
                    });
                    $scope.barCodePage.dataList = billDetail.materialsList;
                    $scope.changeTab(9);
                });
            };
            $scope.createMaterialBarcode = function () {
                if (!$scope.barCodePage.currentMaterial.materialsNo) {
                    ybWidget.ShowMessage("没有可打印的条码", MESG_TYPE.Error);
                    return;
                }
                var service = "device";
                var reqUrl = "/barcode/singlePurchasePrint";
                var param = {};
                param.billNo = currentBillItem.billNo;
                param.billId = currentBillItem.billId;
                param.rowNo = currentBillItem.rowNo;
                param.materialsNo = $scope.barCodePage.currentMaterial.materialsNo;
                param.materialsDes = $scope.barCodePage.currentMaterial.materialsDes;
                param.totalQty = $scope.barCodePage.detailInfo.totalQty;
                param.detailList = [];
                angular.forEach($scope.barCodePage.packList, function (item) {
                    var detailItem = {};
                    detailItem.barcodeDesc = $scope.barCodePage.detailInfo.barcodeDesc;
                    detailItem.model = $scope.barCodePage.detailInfo.model;
                    detailItem.orawyd = $scope.barCodePage.detailInfo.orawyd;
                    detailItem.currentQty = item.currentQty;
                    detailItem.vinid = item.vinid;
                    param.detailList.push(detailItem);
                });
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.createBarcode(currentBillItem); // 刷新当前页面数据
                });
            };

            function setEachPack() {
                $scope.barCodePage.packList = [];
                var eachPackNum = Math.floor($scope.barCodePage.detailInfo.totalQty / $scope.barCodePage.detailInfo.packNum);
                for (var i = 0; i < $scope.barCodePage.detailInfo.packNum; i++) {
                    var objData = {
                        currentQty: eachPackNum,
                        vinid: ''
                    };
                    if (i == $scope.barCodePage.detailInfo.packNum - 1) {
                        objData.currentQty = Number((objData.currentQty + $scope.barCodePage.detailInfo.totalQty % $scope.barCodePage.detailInfo.packNum).toFixed(3));
                    }
                    $scope.barCodePage.packList.push(objData);

                }
            }

            $scope.pucrchaseOrderTypeChanged = function (purchaseOrderType) {

                if (purchaseOrderType !== 'Z04') { // 不是集团采购
                    clearAllMaterialList();
                    return;
                }
                var param = {
                    filters: {
                        supplierCode: "4040"
                    },
                    pageNum: 1,
                    pageSize: 0

                };
                ybHttp.Post('device', '/companySupplier/list', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (resp.value.list.length > 0) {
                        $scope.orderObj.supplierOrgName = resp.value.list[0].companyName;
                        $scope.orderObj.supplierOrgId = resp.value.list[0].supplierOrgId;
                        $scope.orderObj.drawerOrgName = $scope.orderObj.supplierOrgName;
                        $scope.orderObj.drawerOrgId = $scope.orderObj.supplierOrgId;
                    }
                });
                clearAllMaterialList();

            };

            function clearAllMaterialList() {
                for (var i = $scope.orderObj.materialsList.length - 1; i >= 0; i--) {
                    $scope.orderObj.materialsList.splice(i, 1);
                }
                if ($scope.orderObj.materialsList.length === 0) {
                    $scope.markInfo.allCheckedMaterial = false;
                }
                EventBus.Publish("setMaterial");
            }

            $scope.searchAddress = function (deliveryName) {
                ybWidget.SelectDeliveryAddress({
                    deliveryName: deliveryName,
                    clientReceiveInfo: $scope.onlySelect,
                    supplierOrgId: $scope.orderObj.supplierOrgId
                }).then(function (data) {
                    $scope.orderObj.receiverName = data.receiverName;
                    $scope.orderObj.receiverTel = data.receiverTel;
                    $scope.orderObj.receiverAddress = data.receiverAddress;
                    $scope.orderObj.addressCode = data.addressCode;
                });
            };

            $scope.filterReset = function () {
                $scope.filterCondition = {};
                $scope.orderObj.materialsList = $scope.sourceOrderObj.materialsList;
            };

            $scope.filterDetail = function () {
                var materialsList = [];
                angular.forEach($scope.sourceOrderObj.materialsList, function (item) {
                    var flag = true;
                    if (!!$scope.filterCondition.materialsNo && item.materialsNo !== $scope.filterCondition.materialsNo) {
                        flag = false;
                    }
                    if (!!$scope.filterCondition.purchaseGroup && item.purchaseGroup !== $scope.filterCondition.purchaseGroup) {
                        flag = false;
                    }
                    if (!!$scope.filterCondition.supplierCode) {
                        var flag2 = true;
                        angular.forEach(item.purchaseInfoVOList, function (info) {
                            if (info.supplierSapCode === $scope.filterCondition.supplierCode) {
                                item.supplierCode = info.supplierSapCode;
                                item.supplierOrgName = info.supplierName;
                                flag2 = false;
                            }
                        });
                        if (flag2) {
                            flag = false;
                        }
                    }
                    if (flag) {
                        materialsList.push(item);
                    }
                });
                $scope.orderObj.materialsList = materialsList;
            };

            $scope.go2logistics = function (item) {
                EventBus.Publish('go2otherMenuPage', {
                    name: "app.logistics.handoverBill",
                    params: {
                        orderNo: item.billNo
                    }
                });
            };

            function getUrlParams(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                var parm = window.location.hash.split("?")[1];
                if (parm == null) return null;
                var r = parm.match(reg);
                if (r == null) return null;
                return unescape(r[2]);
            }

            (function () {
                $scope.orderObj.purchaseOrgName = $scope.curOrg.companyName;
                if (!$scope.isZHJCH) {
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'rowNo').hidden = true;
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'deliveryDate').hidden = true;
                } else {
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'rowNo').hidden = false;
                }
                if ($scope.isWJ) {
                    ybWidget.GetTableCol($scope.materielTableConfig.tableCol, 'priceSchemeName').hidden = true;
                }
                materielTableConfig = angular.copy($scope.materielTableConfig);

                getPurchaseLevel();
                getPurchaseOrderType();
                getOrderStatues();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);

                var orderId = getUrlParams("orderId");
                var orderNo = getUrlParams("orderNo");
                if (orderNo) {
                    $scope.condition.billNo = orderNo
                } else if (orderId) {
                    $scope.editApply({
                        billId: orderId
                    });
                }
                getDataList();
            })();
        }]);
})(window, window.angular);